package com.code.config.Shiro;

import com.code.common.utils.JWTUtil;
import com.code.modules.base.model.Resource;
import com.code.modules.base.model.Role;
import com.code.modules.base.model.User;
import com.code.modules.base.service.ResourceService;
import com.code.modules.base.service.RoleService;
import com.code.modules.base.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserService usrService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private ResourceService resourceService;


    /**
     * 必须重写此方法，不然会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }


    /**
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //System.out.println("————身份认证方法————");
        String token = (String) authenticationToken.getCredentials();
        // 解密获得username，用于和数据库进行对比
        String username = JWTUtil.getUsername(token);
        if (username == null || !JWTUtil.verify(token, username)) {
            throw new AuthenticationException("token认证失败！");
        }
        //通过用户账号查找用户
        User user  = usrService.findUserByusername(username);

        if (user == null) {
            throw new AuthenticationException("该用户不存在！");
        }
        int status = user.getStatus();
        if (status == 2) {
            throw new AuthenticationException("该用户已被冻结！");
        }
        return new SimpleAuthenticationInfo(token, token, "Realm");
    }

    /**
     * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        String username = JWTUtil.getUsername(principals.toString());
        //System.out.println("————权限认证————"+username);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        Set<String> roleSet = new HashSet<>();
        Set<String> permissionSet = new HashSet<>();
        //获得该用户角色
        User user = usrService.findUserByusername(username);

        //一个用户多角色， 多角色对应多权限
        List<Role> roles = roleService.findRoleByuserid(user.getId());
        //需要将 role, permission 封装到 Set 作为 info.setRoles(), info.setStringPermissions() 的参数
        for (Role role : roles) {
            roleSet.add(role.getCode());

            List<Resource> permissions = resourceService.findResourceByRoleid(role.getId());
            for(Resource res: permissions) {
                permissionSet.add(res.getCode());
            }
        }
        //设置该用户拥有的角色和权限
        info.setRoles(roleSet);
        info.setStringPermissions(permissionSet);
        return info;
    }









}
